//
//  ChooseMoreObjcViewController.m
//  SafeFoodManagerDemo
//
//  Created by bob on 2017/11/14.
//  Copyright © 2017年 bob. All rights reserved.
//

#import "ChooseMoreObjcViewController.h"
#import "TBChooseTableViewCell.h"
#import "TBTotalHeadView.h"
#import "TBChooseHeadView.h"
#import "ChooseListModel.h"
#import "SingleSearchView.h"
#import "BottomOptionView.h"
@interface ChooseMoreObjcViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)TB_TableView *homeTableView;

@property(nonatomic,strong)SingleSearchView*searchView;

@property(nonatomic,strong)BottomOptionView *BootView;

@property(nonatomic,strong)NSMutableArray *AddArr;

@property(nonatomic,strong)NSMutableArray *ReqArr;

@property(nonatomic,assign)NSInteger TotalNum;

@property(nonatomic,strong)NSMutableDictionary *reqDict;

@property(nonatomic,assign)NSInteger pages;

@property(nonatomic,assign)BOOL isOpen;

@end

@implementation ChooseMoreObjcViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.pages=1;
    
    self.isOpen=YES;
    
    self.reqDict=[NSMutableDictionary dictionaryWithDictionary:self.ListParams];
    
    [self.reqDict setValue:@"1" forKey:@"pageOn"];
    
     [self.reqDict setValue:@"10" forKey:@"pageSize"];
    
     [self.reqDict setValue:[NSString stringWithFormat:@"%ld",self.pages] forKey:@"currentPage"];
    
     [self.reqDict setValue:@"" forKey:@"params"];
    
      [self.view addSubview:self.searchView];
    
    [self.view addSubview:self.BootView];

    [self.view addSubview:self.homeTableView];

    [self loadDatas];//加载数据
    
    // Do any additional setup after loading the view.
}


-(TB_TableView*)homeTableView
{
    if (!_homeTableView) {
        
        CGRect frame;
        
        if (kDevice_Is_iPhoneX) {
            
            frame=CGRectMake(0, 56, SCREEN_WIDTH, SCREEN_HEIGHT-64-56-50-IPhoneXTableHeight);
            
        }else{
            
            frame=CGRectMake(0, 56, SCREEN_WIDTH, SCREEN_HEIGHT-64-56-50);
            
        }
        
        _homeTableView=[[TB_TableView alloc]initWithFrame:frame];
        
        _homeTableView.delegate=self;
        
        _homeTableView.dataSource=self;
        
        _homeTableView.estimatedRowHeight=60;
        
        _homeTableView.tableFooterView=[[UIView alloc]init];
        
        [_homeTableView registerNib:[UINib nibWithNibName:@"TBChooseTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
        
        [_homeTableView registerClass:[TBChooseHeadView class] forHeaderFooterViewReuseIdentifier:@"head1"];
        
         [_homeTableView registerClass:[TBTotalHeadView class] forHeaderFooterViewReuseIdentifier:@"head2"];
        
        [self configScrollViewFooterLoadMore:_homeTableView];
   
    }
    
    return _homeTableView;
}


-(SingleSearchView*)searchView
{
    if (!_searchView) {
        
        TBWeak;
        _searchView=[[SingleSearchView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 56) andSearchPloahe:@"输入关键字" andBlock:^(NSString *Key) {
            
            [weakSelf.homeTableView.mj_footer resetNoMoreData];
            
            [self.ReqArr removeAllObjects];
            
            self.pages=1;
            
            [self.reqDict setValue:[NSString stringWithFormat:@"%ld",self.pages] forKey:@"currentPage"];
            
            NSDictionary *keydic=@{@"keyword":Key};
            
             [self.reqDict setValue:[HelpWay dictionaryToJSON:keydic] forKey:@"params"];
            
            [weakSelf loadDatas];
            
        }];
        
    }
    return _searchView;
}

-(BottomOptionView*)BootView
{
    
    if (!_BootView) {
        
        CGRect frame;
        
        if (kDevice_Is_iPhoneX) {
            
            frame=CGRectMake(0, SCREEN_HEIGHT-64-50-IPhoneXTableHeight, SCREEN_WIDTH, 50);
            
        }else{
            
            frame=CGRectMake(0, SCREEN_HEIGHT-64-50, SCREEN_WIDTH, 50);
        }
        
        _BootView=[[BottomOptionView alloc]initWithFrame:frame];
        
        TBWeak;
        
        _BootView.block=^(NSInteger type)
        {
            
            if (type==1) {
      
                [weakSelf.AddArr removeAllObjects];
                
                [weakSelf.AddArr addObjectsFromArray:weakSelf.ReqArr];
                
                weakSelf.isOpen=YES;
                
                 [weakSelf.homeTableView reloadData];
                
            }else if (type==2)
            {
                [weakSelf.AddArr removeAllObjects];
                
                weakSelf.isOpen=NO;
                
                [weakSelf.homeTableView reloadData];
                
            }else{

                weakSelf.block(weakSelf.AddArr,weakSelf.AddArr.count);
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }
            
        };
        
    }
    
    return _BootView;
}


-(NSMutableArray*)AddArr
{
    if (!_AddArr) {
        
        _AddArr=[NSMutableArray array];
        
        [_AddArr addObjectsFromArray:self.OrinArr];
        
     
        
    }
    
    return _AddArr;
}

-(NSMutableArray*)ReqArr
{
    if (!_ReqArr) {
        
        _ReqArr=[NSMutableArray array];
        
    }
    
    return _ReqArr;
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    return 2;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    if (section==0) {
        
        if (self.isOpen) {
            
            return self.AddArr.count;
            
        }else{
            
            return 0;
        }
        
        
    }
    
    return self.ReqArr.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    TBChooseTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    if (indexPath.section==0) {
        
        ChooseListItems *items=self.AddArr[indexPath.row];
        
        cell.isHidenBtn=NO;
        
        cell.NameLabel.text=items.name;
        
        cell.Dblock=^(UITableViewCell *cell)
        {
            
            [self.AddArr removeObjectAtIndex:indexPath.row];
            
            [self.homeTableView reloadData];
            
        };
        
    }else{
        
         ChooseListItems *items=self.ReqArr[indexPath.row];
        
        cell.isHidenBtn=YES;
        
        cell.NameLabel.text=items.name;
        
        cell.Dblock=^(UITableViewCell *cell)
        {
            
            
        };
        
    }
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return UITableViewAutomaticDimension;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==1) {
        
     //判断是否存在
       ChooseListItems *items=self.ReqArr[indexPath.row];
        
        BOOL isAdd=NO;
        
        for (ChooseListItems *subitem in self.AddArr) {
            
            if ([subitem.value isEqualToString:items.value]) {
                
                isAdd=YES;
                
                [MBProgressHUD showWarnMessage:@"此项已经添加过"];
            
            }
            
        }

        if (!isAdd) {
            
            [self.AddArr addObject:items];
            
            [self.homeTableView reloadData];
            
        }
      
    }
    
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    return 41;
    
}



-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    if (section==0) {
        
        TBChooseHeadView *head=[tableView dequeueReusableHeaderFooterViewWithIdentifier:@"head1"];
        
        head.tipStr=[NSString stringWithFormat:@"已经选择%ld",self.AddArr.count];
        
        head.isOpen=self.isOpen;
        
        UITapGestureRecognizer *tap=[UITapGestureRecognizer bk_recognizerWithHandler:^(UIGestureRecognizer *sender, UIGestureRecognizerState state, CGPoint location) {
            
            self.isOpen=!self.isOpen;
            
            [self.homeTableView reloadData];
            
        }];
        
        [head addGestureRecognizer:tap];
        
        return head;
        
    }else{
        
        TBTotalHeadView *head=[tableView dequeueReusableHeaderFooterViewWithIdentifier:@"head2"];
        
        head.tipStr=[NSString stringWithFormat:@"一共找到%ld条记录",self.TotalNum];
        
        return head;
        
    }
    
    
}


-(void)loadDatas
{
    [self showLoadingAnimation];
    
    BaseReqApi *Api=[[BaseReqApi alloc]initWithRequestUrl:self.ListUrl andrequestTime:5 andParams:self.reqDict andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:YES];
    
    [Api StarRequest:^(TBResponseStatus responseStatus, NSString *message, id responseObject) {
        
        [self stopLoadingAnimation];
        
        [self mjEndRefreshing:_homeTableView];

        if (responseStatus==1) {
            //请求成功
            //将数据转化成统一的模型
            
            self.TotalNum=[responseObject[@"totalRecord"]integerValue];
            
            NSArray *arr=responseObject[@"data"];
            
            if (self.pages!=1&&arr.count==0) {
                
                [self.homeTableView.mj_footer endRefreshingWithNoMoreData];
            }
            
            for (NSDictionary *dic in arr) {
                
                ChooseListItems *items=[ChooseListItems new];
                
                if ([self.ListUrl isEqualToString:@"/index.php/FoodCheckApi/shopList.json"]) {
                    
                    //商户
                    
                    items.name=dic[@"shopName"];
                    
                    items.value=[dic[@"shopId"]stringValue];
                    
                    
                }else if ([self.ListUrl isEqualToString:@"/index.php/FoodCheckApi/marketList.json"])
                {
                 
                    //开办方
                    
                    items.name=dic[@"Name"];
                    
                    items.value=[dic[@"marketId"]stringValue];
                    
                    
                }else if ([self.ListUrl isEqualToString:@"/index.php/FoodCheckApi/checkerList.json"])
                {
                    //检查员
                    
                    items.name=dic[@"staffName"];
                    
                    items.value=[dic[@"staffId"]stringValue];
                    
                }else if ([self.ListUrl isEqualToString:@"/index.php/FoodCheckApi/inspectSubjectList.json"])
                {
                 //检查主题
                    
                    items.name=dic[@"subjectName"];
                    
                    items.value=[dic[@"subjectId"]stringValue];
                    
                }else if ([self.ListUrl isEqualToString:@"/index.php/FoodCheckApi/supplierList.json"])
                {
                    //检查主题
                    
                    items.name=dic[@"supplierName"];
                    
                    items.value=[dic[@"supplierId"]stringValue];
                    
                }
      
                [self.ReqArr addObject:items];
            }
            
            
            [self.homeTableView reloadData];
          
        }else if (responseStatus==0||responseStatus==2)
        {
            [MBProgressHUD showErrorMessage:message];
            
            self.Type=TBReqFalie;
            
        }else{
            //404需要重新登录了
            
            [UIAlertView bk_showAlertViewWithTitle:message message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                
                if (buttonIndex==1) {
                    
                    [self GotoLoginVC];
                }
                
            }];
            
        }
        
        
    }];
    
    
}

- (void)actionMJFooterLoadMore
{
    self.pages++;
    
     [self.reqDict setValue:[NSString stringWithFormat:@"%ld",self.pages] forKey:@"currentPage"];
    
    [self loadDatas];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
